<?php


namespace App\Macros;


use Illuminate\Container\Container;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;

class ApiPaginator extends LengthAwarePaginator implements Macro
{

    public static function inject()
    {
        Builder::macro('apiPaginate', function($perPage = 15, $columns = ['*'], $pageName = 'page', $page = null){
            $page = $page ?: Paginator::resolveCurrentPage($pageName);

            $perPage = request()->get('pageSize') ? : $perPage;
            $total = $this->toBase()->getCountForPagination();
            $items = $total ? $this->forPage($page, $perPage)->get($columns) : collect();

            $currentPage = $page;
            $options = [
                'path' => Paginator::resolveCurrentPath(),
                'pageName' => $pageName,
            ];

            return Container::getInstance()->makeWith(ApiPaginator::class,  compact(
                'items', 'total', 'perPage', 'currentPage', 'options'
            ));
        });
    }

    public function toArray()
    {
        return [
            'items' => $this->items->toArray(),
            'pagination' => [
                'totalCount' => $this->total(),
                'pageSize'=> $this->perPage(),
            ]
        ];
    }


}
